import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useAddressStore = defineStore('address', () => {
  // 地址列表
  const addressList = ref([
    {
      id: 1,
      name: '张三',
      phone: '13800138000',
      province: '北京市',
      city: '北京市',
      district: '朝阳区',
      address: '三里屯SOHO 1号楼 1001室',
      isDefault: true,
      tag: '家'
    },
    {
      id: 2,
      name: '李四',
      phone: '13900139000',
      province: '上海市',
      city: '上海市',
      district: '浦东新区',
      address: '陆家嘴金融中心 2号楼 2002室',
      isDefault: false,
      tag: '公司'
    }
  ])

  // 计算属性
  const defaultAddress = computed(() => {
    return addressList.value.find(addr => addr.isDefault) || addressList.value[0]
  })

  const addressCount = computed(() => addressList.value.length)

  // 添加地址
  const addAddress = (addressData) => {
    const newAddress = {
      ...addressData,
      id: Date.now(), // 使用时间戳作为临时ID
      isDefault: addressData.isDefault || false
    }

    // 如果设置为默认地址，先取消其他地址的默认状态
    if (newAddress.isDefault) {
      addressList.value.forEach(addr => addr.isDefault = false)
    }

    addressList.value.push(newAddress)
    saveToLocalStorage()
    return newAddress
  }

  // 更新地址
  const updateAddress = (id, addressData) => {
    const index = addressList.value.findIndex(addr => addr.id === id)
    if (index !== -1) {
      const updatedAddress = {
        ...addressList.value[index],
        ...addressData
      }

      // 如果设置为默认地址，先取消其他地址的默认状态
      if (updatedAddress.isDefault) {
        addressList.value.forEach(addr => addr.isDefault = false)
      }

      addressList.value[index] = updatedAddress
      saveToLocalStorage()
      return updatedAddress
    }
    return null
  }

  // 删除地址
  const deleteAddress = (id) => {
    const index = addressList.value.findIndex(addr => addr.id === id)
    if (index !== -1) {
      const deletedAddress = addressList.value[index]
      addressList.value.splice(index, 1)

      // 如果删除的是默认地址，且还有其他地址，设置第一个为默认
      if (deletedAddress.isDefault && addressList.value.length > 0) {
        addressList.value[0].isDefault = true
      }

      saveToLocalStorage()
      return true
    }
    return false
  }

  // 设置默认地址
  const setDefaultAddress = (id) => {
    addressList.value.forEach(addr => {
      addr.isDefault = addr.id === id
    })
    saveToLocalStorage()
  }

  // 根据ID获取地址
  const getAddressById = (id) => {
    return addressList.value.find(addr => addr.id === id)
  }

  // 保存到本地存储
  const saveToLocalStorage = () => {
    try {
      localStorage.setItem('addressList', JSON.stringify(addressList.value))
    } catch (error) {
      console.error('保存地址到本地存储失败:', error)
    }
  }

  // 从本地存储加载
  const loadFromLocalStorage = () => {
    try {
      const saved = localStorage.getItem('addressList')
      if (saved) {
        addressList.value = JSON.parse(saved)
      }
    } catch (error) {
      console.error('从本地存储加载地址失败:', error)
    }
  }

  // 验证地址数据
  const validateAddress = (addressData) => {
    const required = ['name', 'phone', 'province', 'city', 'district', 'address']
    const missing = required.filter(field => !addressData[field])
    
    if (missing.length > 0) {
      return {
        valid: false,
        message: `请填写${missing.join('、')}`
      }
    }

    // 验证手机号
    const phoneRegex = /^1[3-9]\d{9}$/
    if (!phoneRegex.test(addressData.phone)) {
      return {
        valid: false,
        message: '请输入正确的手机号码'
      }
    }

    return { valid: true }
  }

  return {
    addressList,
    defaultAddress,
    addressCount,
    addAddress,
    updateAddress,
    deleteAddress,
    setDefaultAddress,
    getAddressById,
    saveToLocalStorage,
    loadFromLocalStorage,
    validateAddress
  }
})
